package com.ksl.kinglockguard.widget;

import java.io.File;

import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.BounceInterpolator;
import android.view.animation.OvershootInterpolator;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ksl.kinglockguard.R;
import com.ksl.kinglockguard.activity.GameListActivity;
import com.ksl.kinglockguard.bitmap.ImageLoader;
import com.ksl.kinglockguard.data.Constants;
import com.ksl.kinglockguard.data.SharePreferenceSdkData;
import com.ksl.kinglockguard.data.UserCountHabit;
import com.ksl.kinglockguard.domain.MainNews;
import com.ksl.kinglockguard.utils.ImageUtils;
import com.ksl.kinglockguard.utils.NetUtil;
import com.ksl.kinglockguard.utils.SdcardFileUtil;
import com.ksl.kinglockguard.widget.shimmer.Shimmer;
import com.ksl.kinglockguard.widget.shimmer.ShimmerTextView;
import com.lsk.open.core.MyLog;
import com.lsk.open.core.net.NetHeadUtils;
import com.lsk.open.core.utils.KingsFileUtils;
import com.lsk.open.core.utils.StringUtils;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class ScreenLockView extends RelativeLayout {
	public static final String SHOW_SMALL_IMAGE = "1";

	private static final String DEFAULT_WALLPAER = "deflaut_wallpaper";
	private static final String DEFAULT_WALLPAER_BLUR = "deflaut_wallpaper.blur";

	/** 整个内容的布局 **/
	private RelativeLayout lay_container;
	/** 高亮显示的文本 **/
	private ShimmerTextView stv_left_to_detail;
	/** 锁屏的背景图片 **/
	private ImageView iv_screen_image;
	/** 锁屏下方的移动箭头 **/
	private ImageView iv_icon_arrow;
	/** 电量ICon **/
	private ImageView iv_battery;
	/** wifi信号icon **/
	private ImageView iv_net_type;
	/** 打开H5游戏列表界面 **/
	private ImageView iv_h5icon;
	/** 锁屏的模糊图片 **/
	private ImageView iv_blur_image;
	private ImageView iv_news_icon;
	/** 内容Item的布局 **/
	private RelativeLayout lay_news_content;
	/** 内容标题 **/
	private TextView tv_news_title;
	/** 内容的icon **/

	private int screenWidth;
	private boolean isPause;
	private AnimatorSet set;
	private Shimmer shimmer;
	private float downX, lastX;

	private GestureDetector gd;
	private LockListener listener;
	private boolean isAnimating;
	private Context mContext;

	public ScreenLockView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		mContext =context;
		init();
		setListener();
		
	}

	public ScreenLockView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
		mContext =context;
	}

	public ScreenLockView(Context context) {
		this(context, null);
		mContext =context;
	}

	private void init() {
		screenWidth = getContext().getResources().getDisplayMetrics().widthPixels;
		inflate(getContext(), R.layout.lock_screen_lock_view, this);
		iv_screen_image = (ImageView) findViewById(R.id.iv_screen_image);
		iv_blur_image = (ImageView) findViewById(R.id.iv_blur_image);
		iv_net_type = (ImageView) findViewById(R.id.iv_wifi);
		iv_battery = (ImageView) findViewById(R.id.iv_battery);
		iv_h5icon = (ImageView) findViewById(R.id.iv_h5_icon);
		lay_container = (RelativeLayout) findViewById(R.id.lay_container);
		stv_left_to_detail = (ShimmerTextView) findViewById(R.id.stv_left);
		iv_icon_arrow = (ImageView) findViewById(R.id.iv_icon_arrow);
		shimmer = new Shimmer();
		shimmer.start(stv_left_to_detail);
		lay_news_content = (RelativeLayout) findViewById(R.id.lay_news_content);
		tv_news_title = (TextView) findViewById(R.id.tv_news_title);
		iv_news_icon = (ImageView) findViewById(R.id.iv_news_icon);
		handler.sendEmptyMessageDelayed(0, 200);

	}

	private void setListener() {
		lay_news_content.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (listener != null) {
					listener.itemClick();
				}
			}
		});
		gd = new GestureDetector(getContext(),
				new GestureDetector.SimpleOnGestureListener() {
					@Override
					public boolean onFling(MotionEvent e1, MotionEvent e2,
							float velocityX, float velocityY) {
						if (e2.getX() - e1.getX() > 100 && velocityX > 500) {
							if (listener != null && !isAnimating) {
								listener.compute(0, true);
							}
							return true;
						}
						return super.onFling(e1, e2, velocityX, velocityY);
					}
				});
		iv_h5icon.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				UserCountHabit.setUserCount(getContext(), UserCountHabit.H5_FROM_SCREEN);
//				MobclickAgent.onEvent(getContext(), "h5_from_screen", UserCountHabit.H5_FROM_SCREEN);
				Intent intent = new Intent();
    			intent.setClass(getContext(), GameListActivity.class);
    			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//    			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    			getContext().startActivity(intent);
    			unLock();
			}
		});
	}

	@SuppressLint("NewApi")
	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			if (!isPause) {
				ObjectAnimator oa = ObjectAnimator.ofFloat(iv_icon_arrow,
						"alpha", 0.3f, 1.0f, 0.0f);
				oa.setDuration(800);
				ObjectAnimator oa2 = ObjectAnimator.ofFloat(iv_icon_arrow, "x",
						screenWidth / 3, screenWidth * 2 / 3);
				oa2.setDuration(800);
				set = new AnimatorSet();
				set.playTogether(oa, oa2);
				set.start();
				set.addListener(new AnimatorListener() {

					@Override
					public void onAnimationStart(Animator animation) {
					}

					@Override
					public void onAnimationRepeat(Animator animation) {
					}

					@Override
					public void onAnimationEnd(Animator animation) {
						handler.sendEmptyMessageDelayed(0, 2000);
					}

					@Override
					public void onAnimationCancel(Animator animation) {
					}
				});
			}
		}
	};

	public void setNewsItemVisibility(int v) {
		lay_news_content.setVisibility(v);
	}

	public void screenOn() {
		if (lay_news_content.getVisibility() != View.VISIBLE) {
			return;
		}
		ScaleAnimation sa = new ScaleAnimation(0.6f, 1.0f, 0.6f, 1.0f,
				Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
				0.5f);
		sa.setInterpolator(new BounceInterpolator());
		sa.setDuration(500);
		AlphaAnimation aa = new AlphaAnimation(0.0f, 1.0f);
		aa.setDuration(500);

		AnimationSet set = new AnimationSet(false);
		set.addAnimation(sa);
		set.addAnimation(aa);
		lay_news_content.startAnimation(set);
		startShimmer();
	}

	/**
	 * 解锁后，view的位置已经跑出屏幕外边。 需要复位到原始位置
	 */
	public void resetLock() {
		iv_screen_image.setAlpha(1.0f);
		lay_container.setTranslationX(0);
	}

	/**
	 * 滑动结束后，滑动距离小于屏幕的1/2，归位
	 */
	public void resetView() {
		ObjectAnimator alpha = ObjectAnimator.ofFloat(iv_screen_image, "alpha",
				iv_screen_image.getAlpha(), 1.0f);
		ObjectAnimator oa = ObjectAnimator.ofFloat(lay_container,
				"translationX", lay_container.getTranslationX(), 0f);
		oa.setInterpolator(new OvershootInterpolator(1.5f));
		AnimatorSet set = new AnimatorSet();
		set.setDuration(500);
		set.playTogether(alpha, oa);
		set.start();
	}

	private ObjectAnimator tranAnimator;

	/**
	 * 滑动结束后，距离超过屏幕1/2，执行解锁动画
	 */
	public void unLock() {
		isAnimating = true;
		final float x = lay_container.getTranslationX();
		tranAnimator = null;
		tranAnimator = ObjectAnimator.ofFloat(lay_container, "translationX", x,
				(float) screenWidth);
		tranAnimator.addListener(new AnimatorListener() {
			@Override
			public void onAnimationEnd(Animator animation) {
				isAnimating = false;
				if (listener != null) {
					listener.unlock();
				}
				new Thread(new Runnable() {
					@Override
					public void run() {
						UserCountHabit.setUserCount(mContext,
								UserCountHabit.DESK_RIGHT);
					}
				}).start();
			}

			@Override
			public void onAnimationStart(Animator animation) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onAnimationCancel(Animator animation) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onAnimationRepeat(Animator animation) {
				// TODO Auto-generated method stub
				
			}
		});
		tranAnimator.setDuration(300);
		tranAnimator.start();
	}

	/**
	 * 开始高亮显示“点击查看”
	 */
	public void startShimmer() {
		if (shimmer != null) {
			shimmer.start(stv_left_to_detail);
		}
	}

	/**
	 * 锁屏图片或者数据没有下载下来的时候，需要设置壁纸为锁屏背景
	 */
	public boolean setDefaultWallpager() {
		boolean result = false;
		refreshH5Icon();
		recycleBitmap();
		Bitmap screenImageBitmap = BitmapFactory.decodeFile(Constants.FOLDER_PICTURE
				+ DEFAULT_WALLPAER);
		if(screenImageBitmap == null){
			Drawable wallDraw = WallpaperManager.getInstance(
					getContext()).getDrawable();
			BitmapDrawable bd = (BitmapDrawable) wallDraw;
			screenImageBitmap = bd.getBitmap();
		}
		if(!screenImageBitmap.isRecycled()){
			iv_screen_image.setBackgroundDrawable(new BitmapDrawable(
					screenImageBitmap));
			result = true;
		}
		MyLog.e("wmm", "screenImageBitmap : "+screenImageBitmap);
		Bitmap blurImageBitmap = BitmapFactory.decodeFile(Constants.FOLDER_PICTURE
				+ DEFAULT_WALLPAER_BLUR);
		if(blurImageBitmap != null && !blurImageBitmap.isRecycled()){
			iv_blur_image
			.setBackgroundDrawable(new BitmapDrawable(blurImageBitmap));
		}
		MyLog.e("wmm", "blurImageBitmap : "+blurImageBitmap);
		return result;
//		iv_screen_image.setBackgroundResource(R.drawable.default_normal);
//		iv_blur_image.setBackgroundResource(R.drawable.default_blur);
	}

//	Bitmap screenImageBitmap;
//	Bitmap blurImageBitmap;

	public synchronized  void recycleBitmap() {
		// add by lijc for memory recycle 2014-11-27 start
//		if (screenImageBitmap != null&&!screenImageBitmap.isRecycled()) {
//            iv_screen_image.setImageBitmap(null);
//			screenImageBitmap.recycle();
//			screenImageBitmap = null;
//		}
//		if (blurImageBitmap != null&&!blurImageBitmap.isRecycled()) {
//            iv_blur_image.setImageBitmap(null);
//			blurImageBitmap.recycle();
//			blurImageBitmap = null;
//		}
		// add by lijc for memory recycle 2014-11-27 end
	}
	
	private void refreshH5Icon(){
		if(!SharePreferenceSdkData.getH5GameStatus(getContext())){
			iv_h5icon.setVisibility(View.GONE);
		}else{
			iv_h5icon.setVisibility(View.VISIBLE);
		}
	}
	
	
	public void setImageVisibility(int v){
		iv_blur_image.setVisibility(v);
		iv_screen_image.setVisibility(v);
	}
	
	public void setTitleVisibility(int v){
		tv_news_title.setVisibility(v);
	}
	
	public void setNewsItemTitle(String title){
		tv_news_title.setText(title);
	}

	/**
	 * Screen-Off时，刷新锁屏界面的数据
	 * 
	 * @param news
	 * @return true 如果更新成功，otherwise false
	 */
	public synchronized boolean refreshNews(MainNews news) {
		refreshH5Icon();
		boolean result = false;
		String imageUrl = news.getLargeImageUrl();
		File file = null;
		try {
			file = SdcardFileUtil.getFile(
					ImageLoader.LOCK_SCREEN_PICTURE, imageUrl);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		MyLog.i("jyh", "~~~~~File file is ~~~~" + file);
		if (file != null && file.exists()) {
			MyLog.i("jyh", "~~~~~~~~~file != null && file.exists()~~~~~~");
			long start = System.currentTimeMillis();

			recycleBitmap();

			Bitmap screenImageBitmap = ImageLoader.decodeFile(file, ImageLoader.LOCK_SCREEN_PICTURE);
			MyLog.e("wmm", "refreshNews screenImageBitmap : "+screenImageBitmap);
			MyLog.i("wmm", "decode time : "
					+ (System.currentTimeMillis() - start));

			if (screenImageBitmap != null&&!screenImageBitmap.isRecycled()) {
				// TODO lijc
//				iv_screen_image.setBackgroundDrawable(new BitmapDrawable(
//						screenImageBitmap));
				iv_screen_image.setImageBitmap(screenImageBitmap);
				File blurFile = null;
				try {
					blurFile = SdcardFileUtil.getFile(
							ImageLoader.LOCK_BLUR_PICTURE, imageUrl);
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				// Bitmap blurBmp = null;
				Bitmap blurImageBitmap = null;
				if (!blurFile.exists()) {
					blurImageBitmap = ImageUtils.getBlurAndSaveFile(file,
							getContext());
				} else {
					blurImageBitmap = BitmapFactory.decodeFile(blurFile
							.getAbsolutePath());
				}
				if (blurImageBitmap != null&!blurImageBitmap.isRecycled()) {
//					iv_blur_image.setBackgroundDrawable(new BitmapDrawable(
//							blurImageBitmap));
					iv_blur_image.setImageBitmap(blurImageBitmap);
					MyLog.e("wmm", "refreshNews blurImageBitmap : "+blurImageBitmap);
				} else {
//					iv_blur_image.setBackgroundDrawable(new BitmapDrawable(// 防止内存报错，此类情况不生成
//							screenImageBitmap));

					iv_blur_image.setImageBitmap(null);
				}
				tv_news_title.setText(StringUtils.ToDBC(news.getTitle()));
				if (SHOW_SMALL_IMAGE.equals(news.getShowSmallImage())) {
					File smallImage = null;
					try {
						smallImage = SdcardFileUtil.getFile(ImageLoader.LOCK_DESK_ICON,news.getSmallImageUrl());
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if (!smallImage.exists()
							&& !NetHeadUtils.isNetWorking(getContext())) {
						iv_news_icon.setVisibility(View.GONE);
					} else {
						iv_news_icon.setVisibility(View.VISIBLE);
						ImageLoader.getInstance(getContext()).DisplayImage(
								news.getSmallImageUrl(), iv_news_icon, false,
								ImageLoader.LOCK_DESK_ICON);
					}
				} else {
					iv_news_icon.setVisibility(View.GONE);
				}
				result = true;
				MyLog.i("wmm", "all time : "
						+ (System.currentTimeMillis() - start));
				MyLog.i("jyh1", "~~~~screenImageBitmap address is "+screenImageBitmap);
				MyLog.i("jyh1", "~~~~blurImageBitmap address is "+blurImageBitmap);
			}
		}
		return result;
	}

	/**
	 * 刷新电量
	 */
	public void refreshBatteryLevel(int status, int level) {
		// TODO 判断并更改电量显示
		switch (status) {
		case BatteryManager.BATTERY_STATUS_CHARGING: // 正在充电
			iv_battery.setImageResource(R.drawable.icon_battery_charging);
			break;
		case BatteryManager.BATTERY_STATUS_UNKNOWN:
		case BatteryManager.BATTERY_STATUS_DISCHARGING:
		case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
		case BatteryManager.BATTERY_STATUS_FULL:
			iv_battery.setImageResource(R.drawable.battery_level_list);
			iv_battery.setImageLevel(level);
			break;
		}
	}

	/**
	 * 刷新wifi信号
	 */
	public void refreshWifiLevel(int status, int level) {
		// TODO 判断并更改Wifi显示
		switch (status) {
		case WifiManager.WIFI_STATE_UNKNOWN:
		case WifiManager.WIFI_STATE_DISABLING:
		case WifiManager.WIFI_STATE_DISABLED:
			iv_net_type.setVisibility(View.GONE);
			break;
		case WifiManager.WIFI_STATE_ENABLING:
		case WifiManager.WIFI_STATE_ENABLED:
			iv_net_type.setVisibility(View.VISIBLE);
			iv_net_type.setImageResource(R.drawable.wifi_level_list);
			iv_net_type.setImageLevel(level);
			break;
		}
	}

	/**
	 * 刷新移动网络类型
	 */
	public void refreshNetType(String type) {
		if (NetUtil.NETWORK_WIFI.equals(type)) {
			iv_net_type.setImageResource(R.drawable.wifi_level_list);
			iv_net_type.setVisibility(View.VISIBLE);
		} else if (NetUtil.NETWORK_2G.equals(type)) {
			iv_net_type.setImageResource(R.drawable.icon_2g);
		} else if (NetUtil.NETWORK_3G.equals(type)) {
			iv_net_type.setImageResource(R.drawable.icon_3g);
			iv_net_type.setVisibility(View.VISIBLE);
		} else if (NetUtil.NETWORK_4G.equals(type)) {
			iv_net_type.setImageResource(R.drawable.icon_4g);
			iv_net_type.setVisibility(View.VISIBLE);
		} else {
			iv_net_type.setVisibility(View.GONE);
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (gd.onTouchEvent(event)) {
			return true;
		}
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			MyLog.i("wmm", "ACTION_DOWN  isAnimating:" + isAnimating);
			downX = event.getX();
			lastX = event.getX();
			break;
		case MotionEvent.ACTION_MOVE:
			final float x = event.getX();
			final int offset = (int) (x - lastX);
			lastX = x;
			lay_container.setTranslationX(lay_container.getTranslationX()
					+ offset);
			float tX = lay_container.getTranslationX();
			if (tX < 0) {
				lay_container.setTranslationX(0);
			}
			if (tX > 0) {
				float per = tX / (screenWidth / 2);
				if (per > 1) {
					iv_screen_image.setAlpha(0f);
				} else {
					iv_screen_image.setAlpha(1 - per);
				}
			}
			break;
		case MotionEvent.ACTION_UP:
		case MotionEvent.ACTION_CANCEL:
			MyLog.i("wmm", "ACTION_CANCEL" + "   isAnimating" + isAnimating);
			if (listener != null && !isAnimating) {
				listener.compute(lay_container.getTranslationX(), false);
			}
			break;

		default:
			break;
		}
		return false;
	}

	public void setLockListener(LockListener l) {
		listener = l;
	}

	/**
	 * 锁屏界面的回调接口
	 * 
	 * @author Administrator
	 * 
	 */
	public interface LockListener {
		/**
		 * 点击锁屏界面的内容区块时的回调
		 */
		public void itemClick();

		/**
		 * 滑动结束后的回调，由实现此接口的类决定做什么操作
		 * 
		 * @param tx
		 *            松手时的X轴的位置
		 * @param isFling
		 *            是否是Fling操作
		 */
		public void compute(float tx, boolean isFling);

		/**
		 * 解锁后的回调方法
		 */
		public void unlock();
	}
}
